import React, { PureComponent } from 'react'
import { connect, history } from '@umijs/max'
import {
  Button, Checkbox, Form, Input, Switch, Modal, message, Radio, Select, TreeSelect,
} from 'antd'
import lodash from 'lodash'
import list2tree from 'list2tree'
import {
  BreadcrumbBar, CreateDiffEditor, ProTable, proTableHeaderWrapperAddButton,
} from '@/components'
import { getHashParameterByName } from '@/utils/helper'
import Tools from '@/utils/Tools'
import { DataPreview, TestModal } from './page-components'
import styles from './index.less'
import {
  requestIdMap, responseIdMap, returnDescId, returnMenuList,
} from '@/utils/utils'
import {
  addNewParamsRow,
  getRealIndexByType,
  selectedApiTypeToColumn,
} from '@/customLibrary/api-create'
import {
  paramDataTypeArr, PAGE_SIZE, descRe, pathRe, lenRe, txtRe,
} from '@/utils/constans'
import ParamsTransferModal from '@/pages/DataService/ProduceApiCreate/page-components/ParamsTransferModal'

const { mergeWith, cloneDeep } = lodash
const { Item } = Form
const { TextArea } = Input
const { Option } = Select
const Bus = Tools.Bus

const descId = returnDescId()
const menuList = returnMenuList(descId)
// 请求参数中的参数类型
const getNavTreeDataFunc2 = list2tree({
  idKey: 'id',
  parentIdKey: 'pid',
  newKey: {
    key: 'id',
    value: 'id',
    title: 'dirName',
  },
})
// lodash 的 merge 所需的 配套方法
const mergeWithFunction = (objValue, srcValue) => srcValue || objValue
// 后端要求不在类型数组中的类型全转化为STRING
const changeOtherType = item => {
  if (item?.fieldName) { // 编辑时 fieldName 为null
    item.paramName = item?.fieldName
  }
  if (!item?.paramDataType || paramDataTypeArr.indexOf(item.paramDataType) === -1) {
    item.paramDataType = 'STRING'
  }
  return item
}

@connect(({ myApiCreate }) => ({ ...myApiCreate }))
class ProduceApiCreate extends PureComponent {
  selectedApiTypeToColumn = selectedApiTypeToColumn.call(this)

  addNewParamsRow = addNewParamsRow.call(this)

  constructor(props) {
    super(props)
    this.state = {
      dataSourceList0: [], // 数据源列表
      dataSourceList1: [], // 数据源列表
      selectedDataSource: '', // 选中的数据源
      tableNameList: [], // 数据表列表
      fieldDataSource: [], // 参数选择 数据源
      fieldLoading: false,
      requestParams: [], // 请求参数设置 数据源
      responseParams: [], // 返回参数设置 数据源
      pageable: 0,
      sql: '',
      apiScript: '',
      loading: false,
      paramsSetModalVisible: false,
      searchLoading: false,
      selectedApiType: 0,
      forceUpdate: 0,
    }
    this.dataSourceForm = React.createRef()
    this.testModalRef = React.createRef()
    this.shellEditorRef = React.createRef()
    this.dataPreviewRef = React.createRef()

    this.reqTableRef = React.createRef()
    this.resTableRef = React.createRef()
    this.paramsTableRef = React.createRef()
  }

  componentDidMount() {
    this.queryGetDataSourceList()
    this.queryGetApiGroup()
    this.descId = getHashParameterByName('id') || ''
    const dirKey = getHashParameterByName('dirKey') || ''
    if (dirKey) {
      this.dataSourceForm.current?.setFieldsValue({ apiGroupId: dirKey })
    }
    this.descId && this.viewDetail(this.descId)
    Bus.addListener('/data-service/api-manage/produce-api-create/res', (arr) => this.createArrByJson(arr, 'response'))
    Bus.addListener('/data-service/api-manage/produce-api-create/req', (arr) => this.createArrByJson(arr, 'request'))
  }

  createArrByJson = (arr, type) => {
    const isArr = arr instanceof Array
    const isArrJson = typeof arr === 'string' && JSON.parse(arr) instanceof Array
    if (!isArr && !isArrJson) return
    const { key, theParamsCopy } = getRealIndexByType.call(this, type)
    if (isArrJson) {
      arr = JSON.parse(arr)
    }
    // eslint-disable-next-line default-case
    switch (type) {
      // eslint-disable-next-line no-lone-blocks
      case 'request': {
        this.setState({
          [key]: [...theParamsCopy, ...arr].map(requestIdMap),
        })
      }
        break
      // eslint-disable-next-line no-lone-blocks
      case 'response': {
        this.setState({
          [key]: [...theParamsCopy, ...arr].map(responseIdMap),
        })
      }
        break
    }
  }

  // 脚本OnChange 实时更新数据
  getParamByShell = (sql) => {
    this.setState({
      sql,
    })
  }

  // 查看详情
  viewDetail = (id) => {
    this.props.dispatch({
      type: 'myApiCreate/queryGetDataApiDetailById',
      params: {
        id,
      },
      cb: (res) => {
        const { status, msg, data = {} } = res || {}
        if (status === 200) {
          const {
            apiType: selectedApiType,
            datasourceId: selectedDataSource,
            outputParamResponses,
            inputParamResponses,
            pageable,
            apiScript,
            tableName,
            isSecurity,
          } = data
          this.dataSourceForm.current?.setFieldsValue({
            ...data,
            isSecurity: !!isSecurity,
            authType: data.authType ? 1 : 0,
          })
          this.setState({
            selectedDataSource,
            pageable,
            requestParams: [...(inputParamResponses || [])].map(requestIdMap),
            responseParams: [...(outputParamResponses || [])].map(responseIdMap),
            apiScript,
            selectedApiType,
          }, () => {
            tableName && this.handleSelectTableName(tableName, 0, selectedDataSource)
            this.queryGetTableInfoList(selectedDataSource)
          })
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  /*
 * 根据选择参数的列表计算入参和返回参数的列表，调用时机如下
 * 1. 数据表名称切换
 * 2. 选择参数table 设为请求参数，设为返回参数checkbox勾选
 */
  calcSqlResponseParams = (arr) => {
    const newResponseParams = []
    const newRequestParams = []
    const { requestParams = [], responseParams = [] } = this.state
    arr?.forEach((arrItem) => {
      const { paramType, paramName, bindColumnName } = arrItem
      // 脚本模式下，没有绑定字段一说，直接匹配参数名称，如果一致直接复用
      const reqIndex = requestParams.findIndex((item) => item.paramName === paramName)
      const resIndex = responseParams.findIndex((item) => item.bindColumnName === bindColumnName)

      if (reqIndex > -1) {
        arrItem.paramDataType = requestParams[reqIndex].paramDataType || 'STRING'
        arrItem.paramOperator = requestParams[reqIndex].paramOperator || 0
      } else if (resIndex > -1) {
        arrItem.paramDataType = responseParams[resIndex].paramDataType || 'STRING'
      } else {
        arrItem.paramDataType = arrItem.paramDataType || 'STRING'
        arrItem.paramOperator = arrItem.paramOperator || 0
      }
      // 请求参数
      paramType === 0
        ? newRequestParams.push(reqIndex > -1
          ? mergeWith(requestParams[reqIndex], arrItem, mergeWithFunction)
          : arrItem)
        : newResponseParams.push(resIndex > -1
          ? mergeWith(responseParams[resIndex], arrItem, mergeWithFunction)
          : arrItem)
    })
    if (requestParams.length > 0 || responseParams.length > 0) {
      Modal.confirm({
        title: '当前已存在请求参数或返回参数，是否覆盖？',
        okText: '覆盖',
        cancelText: '取消',
        onOk: () => {
          this.setState({
            responseParams: newResponseParams.map(responseIdMap),
            requestParams: newRequestParams.map(requestIdMap),
          })
          message.info('已覆盖')
        },
        onCancel: () => {
          message.info('已取消')
        },
      })
    } else {
      this.setState({
        responseParams: newResponseParams.map(responseIdMap),
        requestParams: newRequestParams.map(requestIdMap),
      })
    }
  }

  // 获取数据源列表
  queryGetDataSourceList = () => {
    this.props.dispatch({
      type: 'myApiCreate/queryGetDataSourceList',
      params: { apiType: 0 },
      cb: (res) => {
        this.setState({
          dataSourceList0: res || [],
        })
      },
    })
    this.props.dispatch({
      type: 'myApiCreate/queryGetDataSourceList',
      params: { apiType: 1 },
      cb: (res) => {
        this.setState({
          dataSourceList1: res || [],
        })
      },
    })
  }

  // 获取API分组
  queryGetApiGroup = () => {
    this.props.dispatch({
      type: 'myApiCreate/queryGetApiGroup',
      params: {},
      cb: (res) => {
        this.setState({
          apiGroupList: getNavTreeDataFunc2(res || []),
        })
      },
    })
  }

  // 选择数据源
  handleSelectDataSource = (val) => {
    this.dataSourceForm.current?.resetFields(['tableName']) // 清空数据表选中的项
    this.setState({
      selectedDataSource: val,
      tableNameList: [], // 清空数据表
      fieldDataSource: [], // 清空参数选择

      requestParams: [],
      responseParams: [],
    }, () => {
      val !== undefined && this.queryGetTableInfoList(val)
    })
  }

  // 获取数据表数据
  queryGetTableInfoList = (val) => {
    this.setState({
      searchLoading: true,
    })
    this.props.dispatch({
      type: 'myApiCreate/queryGetTableInfoList',
      params: {
        dsId: val,
      },
      cb: (res) => {
        this.setState({
          tableNameList: res || [],
          searchLoading: false,
        })
      },
    })
  }

  // 选择数据表，并根据选择的数据表获取字段
  handleSelectTableName = (val, bool, dsId = this.state.selectedDataSource) => {
    const params = this.descId && !bool ? {} : {
      requestParams: [],
      responseParams: [],
    }
    this.setState({
      fieldLoading: true,
      ...params,
    })
    this.paramsTableRef?.current?.resetPageNum()
    this.reqTableRef?.current?.resetPageNum()
    this.resTableRef?.current?.resetPageNum()
    this.props.dispatch({
      type: 'myApiCreate/queryGetTableFieldList',
      params: {
        dsId,
        tableName: val,
      },
      cb: (res) => {
        const fieldDataSourceTemp = res
        if (this.descId) {
          // 根据入参和返回参数列表，设置选择参数表格的勾选状态
          fieldDataSourceTemp?.forEach((fieldItem) => {
            // 默认名称为字段名，默认操作符为等于，默认必填
            fieldItem.paramName = fieldItem.bindColumnName
            fieldItem.paramOperator = 0
            // fieldItem.paramRequire = 1

            this.state.requestParams?.forEach((requestParam) => {
              if (requestParam.bindColumnName === fieldItem.bindColumnName) {
                fieldItem.getData = true
              }
            })

            this.state.responseParams?.forEach((responseParam) => {
              if (responseParam.bindColumnName === fieldItem.bindColumnName) {
                fieldItem.returnData = true
              }
            })
          })
        }

        this.setState({
          fieldDataSource: fieldDataSourceTemp,
          fieldLoading: false,
        })
      },
    })
  }

  handleFieldData = (key, e, index) => {
    const { fieldDataSource } = this.state
    const fieldDataSourceCopy = cloneDeep(fieldDataSource)
    const { pageSize, pageNum } = this.paramsTableRef?.current?.state || {}
    // 使用index区分 勾选的模式
    // -1 < 0 模式为全选
    // * >= 0 为单选
    if (index < 0) {
      fieldDataSourceCopy.forEach((item, itemIndex) => {
        if (itemIndex >= (pageNum - 1) * pageSize && itemIndex < pageNum * pageSize) {
          item[key] = e.target.checked
          item.paramOperator = 0 // 设置操作符为 =
        }
      })
    } else {
      const realIndex = (pageNum - 1) * pageSize + index
      fieldDataSourceCopy[realIndex][key] = e.target.checked
      if (key === 'getData') {
        fieldDataSourceCopy[realIndex].paramOperator = 0 // 设置操作符为 =
      }
    }
    this.setState({
      fieldDataSource: fieldDataSourceCopy,
    }, () => {
      this.calcRequestParamsAndResponseParam()
    })
  }

  /*
 * 根据选择参数的列表计算入参和返回参数的列表，调用时机如下
 * 1. 数据表名称切换
 * 2. 选择参数table 设为请求参数，设为返回参数checkbox勾选
 */
  calcRequestParamsAndResponseParam = () => {
    const newResponseParams = []
    const newRequestParams = []
    const { fieldDataSource, requestParams = [], responseParams = [] } = this.state
    // 遍历参数表格
    fieldDataSource?.forEach((fieldItem) => {
      const { returnData, getData, fieldName = '' } = fieldItem || {}
      // 如果被勾选了，首先看右侧对应的列表是否已存在，
      // 如果存在，直接复用，否则从选择参数表格中复制一份过去
      const resIndex = responseParams.findIndex((item) => item?.bindColumnName === fieldName)
      returnData && newResponseParams.push(resIndex > -1 ? responseParams[resIndex] : { ...fieldItem })
      const reqIndex = requestParams.findIndex((item) => item?.bindColumnName === fieldName)
      getData && newRequestParams.push(reqIndex > -1 ? requestParams[reqIndex] : { ...fieldItem })
    })
    this.clearFiledTemp()
    this.setState(
      {
        responseParams: newResponseParams.map(changeOtherType).map(responseIdMap),
        requestParams: newRequestParams.map(changeOtherType).map(requestIdMap),
      },
    )
  }

  clearFiledTemp = () => {
    const fieldValuesObj = this.dataSourceForm.current.getFieldValue()
    const fieldValuesKey = Object.keys(fieldValuesObj)
    const tempArr = []
    fieldValuesKey.map(item => {
      if (item.indexOf('request') !== -1 || item.indexOf('res') !== -1) {
        tempArr.push(item)
      }
      return null
    })
    this.dataSourceForm.current?.resetFields(tempArr)

    const obj = {}
    tempArr.map(item => {
      obj[item] = ''
      return null
    })
    this.dataSourceForm.current?.setFieldsValue(obj)
  }

  okParamsSetModal = (data) => {
    this.setState({ requestParams: data })
    message.success('设置成功！')
    this.closeParamsSetModal()
  }

  closeParamsSetModal = () => {
    this.setState({ paramsSetModalVisible: false })
  }

  // SQL测试
  sqlTest = () => {
    const { sql } = this.state
    const { dispatch } = this.props
    const bodyRaw = this.shellEditorRef?.current?.getEditorValue()
    const theSql = sql || bodyRaw || ''
    this.dataSourceForm.current?.validateFields(['datasourceId']).then(
      (values) => {
        this.setState({ loading: true })
        theSql.length > 0 ? (
          dispatch({
            type: 'myApiCreate/queryGetParams',
            params: {
              sql: theSql,
              dsId: values.datasourceId,
            },
            cb: (res) => {
              const { status, data, msg } = res
              if (status === 200) {
                this.calcSqlResponseParams(data)
              } else {
                message.error(msg || '服务端错误')
              }
              this.setState({ loading: false })
            },
          })
        ) : (this.setState({ loading: false }))
      },
    )
  }

  // API测试
  apiTest = () => {
    const { requestParams, responseParams, pageable } = this.state
    this.dataSourceForm.current.validateFields().then(
      values => {
        const bodyRaw = this.shellEditorRef?.current?.getEditorValue() || ''
        this.testModalRef?.current?.toggleModal(values, requestParams.filter(item => item && item.paramName && (item.paramOperator || item.paramOperator === 0) && item.paramDataType), responseParams.filter(item => item && item.paramName && item.bindColumnName && item.paramDataType), pageable, bodyRaw)
      },
    )
  }

  save = () => {
    const { requestParams, responseParams, pageable } = this.state
    const requestParamsDataCopy = cloneDeep(requestParams) || []
    const responseParamsDataCopy = cloneDeep(responseParams)
    this.dataSourceForm.current.validateFields().then((values) => {
      const { apiType, isSecurity } = values

      const dispatchType = apiType === 0 ? 'querySaveGuideApi' : 'querySaveScriptApi'

      const params = this.descId ? { id: this.descId } : {}

      const bodyRaw = this.shellEditorRef?.current?.getEditorValue() || ''
      if (apiType === 1) {
        params.apiScript = bodyRaw
      }

      this.props.dispatch({
        type: `myApiCreate/${dispatchType}`,
        params: {
          ...params,
          ...values,
          isSecurity: isSecurity ? 1 : 0,
          pageable,
          inputParamRequest: requestParamsDataCopy.filter(item => item && item.paramName && (item.paramOperator || item.paramOperator === 0) && item.paramDataType).map(item => ({
            ...item,
            paramType: 0,
          })),
          outputParamRequest: responseParamsDataCopy.filter(item => item && item.paramName && item.bindColumnName && item.paramDataType).map(item => ({
            ...item,
            paramType: 1,
          })),
        },
        cb: (res) => {
          const { msg, status } = res || {}
          if (status === 200) {
            history.push('/data-service/api-manage/my-api')
            message.success('操作成功')
          } else {
            message.error(msg || '服务端错误')
          }
        },
      })
    })
  }

  handleApiType = (e) => {
    this.setState({
      fieldDataSource: [],
      requestParams: [],
      responseParams: [],
      selectedApiType: e.target.value,
    })
    this.dataSourceForm.current?.resetFields(['tableName'])
  }

  handlePreviewData = () => {
    const { tableNameList, selectedDataSource } = this.state
    this.dataPreviewRef?.current?.toggleModal(tableNameList, selectedDataSource)
  }

  forceUpdateFn = () => {
    this.setState((prevState) => ({
      forceUpdate: prevState.forceUpdate + 1,
    }))
  }

  render() {
    const {
      dataSourceList0,
      dataSourceList1,
      selectedDataSource,
      tableNameList,
      fieldDataSource,
      fieldLoading,
      requestParams,
      responseParams,
      apiGroupList,
      pageable,
      apiScript,
      loading,
      searchLoading,
      paramsSetModalVisible,
      selectedApiType,
    } = this.state

    // 参数设置的column
    const param_columns = [
      {
        title: (
          <div>
            <Checkbox
              checked={
                (() => {
                  const { pageSize, pageNum } = this.paramsTableRef?.current?.state || {}
                  const fieldDataSourceTemp = fieldDataSource.slice((pageNum - 1) * pageSize, pageNum * pageSize)
                  // 存在的瑕疵，请求参数设置、返回参数设置 的展示顺序不是按点击顺序排序的（与原有的效果一样）
                  return fieldDataSourceTemp?.length > 0 && !fieldDataSourceTemp?.some((item) => !item.getData)
                })()
              }
              // indeterminate={
              //   fieldDataSource?.some((item) => item.getData)
              //   && fieldDataSource?.some((item) => !item.getData)
              // }
              indeterminate={
                (() => {
                  const { pageSize, pageNum } = this.paramsTableRef?.current?.state || {}
                  const fieldDataSourceTemp = fieldDataSource.slice((pageNum - 1) * pageSize, pageNum * pageSize)
                  return fieldDataSourceTemp?.some((item) => item.getData)
                    && fieldDataSourceTemp?.some((item) => !item.getData)
                })()
              }
              disabled={fieldDataSource?.length === 0}
              onChange={(e) => this.handleFieldData('getData', e, -1)}
            />
            <span className={styles.column_title}>设为请求参数</span>
          </div>
        ),
        dataIndex: 'getData',
        width: '20%',
        render: (text, record, index) => (
          <Checkbox
            checked={text}
            onChange={(e) => this.handleFieldData('getData', e, index)}
          />
        ),
      },
      {
        title: (
          <div>
            <Checkbox
              // checked={
              //   fieldDataSource.length > 0
              //   && !fieldDataSource.some((item) => !item.returnData)
              // }
              checked={
                (() => {
                  const { pageSize, pageNum } = this.paramsTableRef?.current?.state || {}
                  const fieldDataSourceTemp = fieldDataSource.slice((pageNum - 1) * pageSize, pageNum * pageSize)
                  // 存在的瑕疵，请求参数设置、返回参数设置 的展示顺序不是按点击顺序排序的（与原有的效果一样）
                  return fieldDataSourceTemp?.length > 0 && !fieldDataSourceTemp?.some((item) => !item.returnData)
                })()
              }
              // indeterminate={
              //   fieldDataSource.some((item) => item.returnData)
              //   && fieldDataSource.some((item) => !item.returnData)
              // }
              indeterminate={
                (() => {
                  const { pageSize, pageNum } = this.paramsTableRef?.current?.state || {}
                  const fieldDataSourceTemp = fieldDataSource.slice((pageNum - 1) * pageSize, pageNum * pageSize)
                  return fieldDataSourceTemp?.some((item) => item.returnData)
                    && fieldDataSourceTemp?.some((item) => !item.returnData)
                })()
              }
              disabled={fieldDataSource.length === 0}
              onChange={(e) => this.handleFieldData('returnData', e, -1)}
            />
            <span className={styles.column_title}>设为返回参数</span>
          </div>
        ),
        dataIndex: 'returnData',
        width: '20%',
        render: (text, record, index) => (
          <Checkbox
            checked={text}
            onChange={(e) => this.handleFieldData('returnData', e, index)}
          />
        ),
      },
      {
        title: '字段名',
        dataIndex: 'fieldName',
        width: '18%',
        ellipsis: true,
      },
      {
        title: '字段类型',
        dataIndex: 'fieldType',
        width: '18%',
        ellipsis: true,
      },
      {
        title: '字段描述',
        dataIndex: 'comment',
        width: '24%',
        ellipsis: true,
        render: (comment) => (comment || '-'),
      },
    ]
    return (
      <div className={styles.my_api_create}>
        <BreadcrumbBar menu={menuList} />
        <div className={styles.back_bar}>
          <i
            className="iconfont icon-zuo"
            onClick={() => { history.push('/data-service/api-manage/my-api') }}
            style={{ cursor: 'pointer' }}
          />
          <span onClick={() => { history.push('/data-service/api-manage/my-api') }}>生成API</span>
        </div>
        <div className={styles.container}>
          <Form
            ref={this.dataSourceForm}
            labelCol={{ span: 3 }}
            wrapperCol={{ span: 10 }}
            autoComplete="off"
          >
            <Item>
              <div className={styles.column}>基础设置</div>
            </Item>
            <Item
              label="开发模式"
              name="apiType"
              initialValue={0}
              rules={[{ required: true, message: '请选择开发模式' }]}
            >
              <Radio.Group onChange={this.handleApiType}>
                <Radio value={0}>向导模式</Radio>
                <Radio value={1}>脚本模式</Radio>
              </Radio.Group>
            </Item>
            <Item
              label="API名称"
              name="apiName"
              rules={[
                { required: true, message: '请输入API名称' },
                {
                  pattern: new RegExp(descRe.reg, 'g'),
                  message: descRe.text,
                }]}
            >
              <Input placeholder="请输入API名称" />
            </Item>
            <Item
              label="API Path"
              name="apiPath"
              rules={[
                { required: true, message: '请输入API Path' },
                {
                  pattern: new RegExp(txtRe.reg, 'g'),
                  message: txtRe.text,
                },
                {
                  pattern: new RegExp(pathRe.reg, 'g'),
                  message: pathRe.text,
                },
              ]}
            >
              <Input placeholder="请输入API Path" />
            </Item>
            <Item
              label="API协议"
              name="apiProtocol"
              rules={[{ required: true, message: '请选择API协议' }]}
              initialValue="0"
            >
              <Radio.Group>
                <Radio value="0">HTTP</Radio>
                {/* <Radio value="1">HTTPS</Radio> */}
              </Radio.Group>
            </Item>
            <Item
              label="请求方式"
              name="apiMethod"
              rules={[{ required: true, message: '请选择请求方式' }]}
              initialValue="GET"
            >
              <Radio.Group>
                <Radio value="GET">GET</Radio>
                <Radio value="POST">POST</Radio>
              </Radio.Group>
            </Item>
            <Item
              label="认证方式"
              name="authType"
              rules={[{ required: true, message: '请选择认证方式' }]}
              initialValue={0}
            >
              <Radio.Group>
                <Radio value={0}>ApiToken认证</Radio>
                <Radio value={1}>UserToken认证</Radio>
              </Radio.Group>
            </Item>
            <Item
              label="API分组"
              name="apiGroupId"
              rules={[
                { required: true, message: '请选择API分组' },
              ]}
            >
              <TreeSelect
                allowClear
                showSearch
                getPopupContainer={(triggerNode) => triggerNode.parentNode}
                // dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={apiGroupList}
                placeholder="请输入选择目录"
                treeDefaultExpandAll
                filterTreeNode={(input, treeNode) => treeNode?.dirName.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                fieldNames={{
                  label: 'dirName', value: 'id', children: 'children',
                }}
              // onChange={this.handleTreeSelect}
              />
            </Item>
            <Item
              label="出入参是否加密"
              name="isSecurity"
              initialValue={false}
              valuePropName="checked"
            >
              <Switch />
            </Item>
            <Item
              label="描述"
              name="apiDesc"
              rules={[
                {
                  pattern: new RegExp(lenRe.reg, 'g'),
                  message: lenRe.text,
                },
              ]}
            >
              <TextArea rows={2} />
            </Item>
            <Item shouldUpdate>
              {(form) => <div
                className={styles.column}
                onDoubleClick={() => {
                  form.validateFields().then((formRes) => {
                    localStorage.setItem('form.validateFields', JSON.stringify(formRes))
                    localStorage.setItem('form.getData', JSON.stringify(requestParams))
                    localStorage.setItem('form.returnData', JSON.stringify(responseParams))
                  })
                }}
              >数据配置</div>}
            </Item>
            <Item
              label="数据源"
              className={styles.require}
            >
              <div className={styles.sign_bar}>
                <Item
                  noStyle
                  label=" "
                  name="datasourceId"
                  rules={[
                    { required: true, message: '请选择数据源' },
                  ]}
                >
                  <Select
                    allowClear
                    showSearch
                    placeholder="请选择数据源"
                    filterOption={(input, option) => option.props?.title?.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    onChange={this.handleSelectDataSource}
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  >
                    {
                      (selectedApiType ? dataSourceList1 : dataSourceList0)?.map(item => (
                        <Option key={item?.id} value={item?.id} title={item?.dsName}>
                          <div className="source-name">
                            {item?.dsName}
                          </div>
                          {<i
                            title={`${
                              // eslint-disable-next-line no-nested-ternary
                              item?.status === null
                                ? ''
                                : item?.status
                                  ? '连接状态：正常'
                                  : '链接状态：失败'
                              }`}
                            className={`iconfont ${
                              // eslint-disable-next-line no-nested-ternary
                              item?.status === null
                                ? ''
                                : item?.status
                                  ? 'icon-chenggong'
                                  : 'icon-shibai1'
                              }`}
                          />}
                        </Option>
                      ))
                    }
                  </Select>
                </Item>
                {
                  selectedApiType === 1
                  && <span
                    className={`${styles.view_btn} ${tableNameList?.length > 0 ? '' : styles.disabled}`}
                    onClick={this.handlePreviewData}
                  >数据预览</span>
                }
              </div>
            </Item>
            <Item
              noStyle
              shouldUpdate
            >
              {(form) => form.getFieldValue('apiType') === 0 && (
                <Item
                  label="数据表"
                  name="tableName"
                >
                  <Select
                    loading={searchLoading}
                    disabled={!selectedDataSource}
                    allowClear
                    showSearch
                    placeholder="请选择数据表"
                    filterOption={(input, option) => option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    onChange={(value) => {
                      this.handleSelectTableName(value, 1)
                    }}
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  >
                    {
                      tableNameList?.map((item, index) => {
                        const { schema = '', tableName = '' } = item
                        let str
                        if (schema) {
                          str = `${schema}.${tableName}`
                        } else {
                          str = tableName
                        }
                        return (
                          <Option
                            key={`${index}_${str}`}
                            value={str}
                            title={str}
                          >{str}</Option>
                        )
                      })
                    }
                  </Select>
                </Item>
              )}
            </Item>
            <Item
              noStyle
              shouldUpdate
            >
              {(form) => form.getFieldValue('apiType') === 0 && (
                <Item
                  label="参数选择"
                  labelCol={{ span: 3 }}
                  wrapperCol={{ span: 21 }}
                  className={styles.sign}
                >
                  <ProTable
                    ref={this.paramsTableRef}
                    loading={fieldLoading}
                    rowKey="fieldName"
                    columns={param_columns}
                    dataSource={fieldDataSource}
                    // pagination={null}
                    forceUpdateFn={this.forceUpdateFn}
                    pageSize={PAGE_SIZE}
                    // scroll={{ x: true, y: 320 }}
                    scroll={{ y: 320 }} // x: true 影响 超出省略
                  />
                </Item>
              )}
            </Item>
            <Item
              noStyle
              shouldUpdate
            >
              {(form) => form.getFieldValue('apiType') === 1 && (
                <Item
                  // name="parentVar"
                  labelCol={{ span: 3 }}
                  wrapperCol={{ span: 21 }}
                  label="查询SQL"
                >
                  <div className={styles.diff_editor_box}>
                    <CreateDiffEditor
                      restData={apiScript}
                      ref={this.shellEditorRef}
                      valueChange={this.getParamByShell}
                      SqlTestDom={<Button
                        className={styles.edit_btn}
                        type="primary"
                        onClick={() => {
                          this.sqlTest()
                        }}
                      >
                        校验SQL参数
                      </Button>}
                      language="sql"
                      theme="vs"
                      editorId="api-shell-editor"
                    />
                  </div>
                </Item>
              )}
            </Item>
            <Item
              label="请求参数设置"
              labelCol={{ span: 3 }}
              wrapperCol={{ span: 21 }}
              className={styles.sign}
            >
              <ProTable
                ref={this.reqTableRef}
                rowKey="id"
                loading={loading}
                columns={this.selectedApiTypeToColumn('request')}
                dataSource={requestParams}
                pageSize={PAGE_SIZE}
                className="table-footer-no-padding"
                scroll={requestParams?.length > 6 ? { x: true, y: 320 } : null}
                components={{
                  header: {
                    wrapper: selectedApiType === 1
                      ? proTableHeaderWrapperAddButton(this.addNewParamsRow('request'), 'requestAddTr', '添加请求参数')
                      : null,
                  },
                }}
              />
            </Item>
            <Item
              label="返回参数设置"
              labelCol={{ span: 3 }}
              wrapperCol={{ span: 21 }}
              className={styles.sign}
            >
              <ProTable
                ref={this.resTableRef}
                loading={loading}
                rowKey="id"
                columns={this.selectedApiTypeToColumn()}
                className="table-footer-no-padding"
                dataSource={responseParams}
                pageSize={PAGE_SIZE}
                scroll={responseParams?.length > 6 ? { x: true, y: 320 } : null}
                components={{
                  header: {
                    wrapper: selectedApiType === 1
                      ? proTableHeaderWrapperAddButton(this.addNewParamsRow('response'), 'responseAddTr', '添加返回参数')
                      : null,
                  },
                }}
              />
            </Item>
            <Item
              label="返回结果分页:"
              colon={false}
              labelCol={{ span: 3 }}
              wrapperCol={{ span: 21 }}
            >
              <Switch
                checked={pageable === 1}
                checkedChildren="开启"
                unCheckedChildren="关闭"
                onChange={(checked) => {
                  this.setState({ pageable: checked ? 1 : 0 })
                }}
              />
            </Item>
          </Form>
        </div>
        <div className={styles.edit_footer}>
          <Button
            className={styles.edit_btn}
            onClick={() => { history.push('/data-service/api-manage/my-api') }}
          >
            取消
          </Button>
          <Button
            className={styles.edit_btn}
            type="primary"
            onClick={this.apiTest}
          >
            API测试
          </Button>
          <Button
            className={styles.edit_btn}
            type="primary"
            onClick={this.save}
          >
            确定
          </Button>
        </div>
        <TestModal ref={this.testModalRef} />
        <ParamsTransferModal data={requestParams} okFn={this.okParamsSetModal} closeFn={this.closeParamsSetModal} visible={paramsSetModalVisible} />
        <DataPreview ref={this.dataPreviewRef} />
      </div>
    )
  }
}

export default ProduceApiCreate
